package renguanyu.app.auth4fx.controller.role;

import javafx.concurrent.Task;
import javafx.scene.control.CheckBox;
import renguanyu.app.auth4fx.model.user.UserRoleDto;
import renguanyu.app.auth4fx.service.role.RolePermissionService;
import renguanyu.app.auth4fx.view.role.RolePermissionListView;

import java.util.List;
import java.util.stream.Collectors;

public class RolePermissionListDeleteController extends Task<Void> {

    private RolePermissionListView rolePermissionListView;
    public RolePermissionListDeleteController(RolePermissionListView rolePermissionListView) {
        this.rolePermissionListView = rolePermissionListView;
    }

    public void execute() {
        System.out.println("RolePermissionListDelete.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private int rows = 0;
    List<CheckBox> rightSelectedCheckBoxes;
    @Override
    protected Void call() {
        System.out.println("RolePermissionListDelete.call");
        UserRoleDto rolePermissionDto = buildRolePermissionDto();
        rows = RolePermissionService.deleteRolePermissionList(rolePermissionDto);
        return null;
    }

    private UserRoleDto buildRolePermissionDto() {
        rightSelectedCheckBoxes = rolePermissionListView.rightCheckBoxContainer.getChildren().stream().map(
            node -> (CheckBox) node
        ).filter(CheckBox::isSelected).collect(Collectors.toList());
        List<String> ids = rightSelectedCheckBoxes.stream().map(e -> e.getProperties().get("id").toString()).collect(Collectors.toList());
        UserRoleDto rolePermissionDto = new UserRoleDto();
        rolePermissionDto.setIds(ids);
        return rolePermissionDto;
    }

    @Override
    protected void running() {
        System.out.println("RolePermissionListDelete.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("RolePermissionListDelete.succeeded");
        if(rows >= 1){
            rolePermissionListView.leftCheckBoxContainer.getChildren().removeAll(rightSelectedCheckBoxes);
            rightSelectedCheckBoxes.forEach(checkBox -> {
                rolePermissionListView.leftCheckBoxContainer.getChildren().add(checkBox);
            });
        }
    }

    @Override
    protected void failed() {
        System.out.println("RoleInfoSave.failed");
    }
}
